package cn.bdqn.websocket;

/**
 * @ProjectName: ycbdqn
 * @Package: cn.bdqn.websocket
 * @Author: huat
 * @Date: 2020/3/18 14:59
 * @Version: 1.0
 */
import java.io.IOException;
import java.util.concurrent.CopyOnWriteArraySet;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.springframework.stereotype.Component;

/**
 * WebSocketServer服务器端
 *
 * @author han
 *
 */
@Component
@ServerEndpoint("/WebSocketServer")
public class WebSocketServer {
    // concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象，若要实现服务端与单一客户端通信的话，可以使用Map来存放，其中Key可以为用户标识
    private static CopyOnWriteArraySet<WebSocketServer> webSockets = new CopyOnWriteArraySet<WebSocketServer>();
    private Session session;

    @OnOpen
    public void onOpen(Session session) {
        this.session = session;
        webSockets.add(this);

    }

    @OnClose
    public void onClose() {
        webSockets.remove(this);

          }

    @OnMessage
    public void onMessage(String message) {
    }

    /**
     *
     * @param session
     * @param error
     */
    @OnError
    public void onError(Session session, Throwable error) {
        error.printStackTrace();
    }

    /**
     * 服务器主动推送消息
     */
    public void sendMessage(String message) {
        try {
            for (WebSocketServer webSocket : webSockets) {
                webSocket.session.getBasicRemote().sendText(message);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }




}
